package com.cc.mydlnademo

import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.*
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.cc.dlnalib.DLNAController
import com.cc.dlnalib.DLNAUtil
import com.cc.dlnalib.STATE_PLAYING
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    val tag = "MainActivityH"
    var menu: Menu? = null

    @SuppressLint("CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        window.decorView.postDelayed({
            NotificationTipActivity.checkNotificationAutoJump(this)
        }, 2000)
        DLNAController.init(this)
        RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .subscribe { isSuccess ->
                if (isSuccess) {
                    vp2.adapter = object : FragmentStateAdapter(this) {
                        override fun getItemCount(): Int {
                            return 2
                        }

                        override fun createFragment(position: Int): Fragment {
                            return when (position) {
                                0 -> VideoListFragment()
                                else -> AudioListFragment()
                            }
                        }
                    }
                }
            }
        ViewModelProvider(
            this,
            ViewModelProvider.NewInstanceFactory()
        ).get(PlayViewModel::class.java)
            .deviceLiveData.observe(this, Observer {
                menu?.findItem(R.id.changeDevice)?.title = it.friendlyName
            })
        if (DLNAController.currentState == STATE_PLAYING) {
            showPlaying()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        this.menu = menu
        menuInflater.inflate(R.menu.menu, menu)
        DLNAController.currentDevice?.let {
            menu.findItem(R.id.changeDevice).setTitle(it.friendlyName)
        }
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.changeDevice) {
            DLNAUtil.showDLNADialog(this) {
                if (DLNAController.currentDevice != it) {
                    Toast.makeText(this, "切换成功", Toast.LENGTH_SHORT).show()
                    ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(
                        PlayViewModel::class.java
                    ).deviceLiveData.value = it
                }
                null
            }
        }
        return super.onOptionsItemSelected(item)
    }

    fun showPlaying() {
        if (supportFragmentManager.findFragmentByTag(PlayFragment::class.java.name) == null) {
            findViewById<View>(R.id.fragment_container).visibility = View.VISIBLE
            supportFragmentManager.beginTransaction()
                .replace(R.id.fragment_container, PlayFragment(), PlayFragment::class.java.name)
                .commitAllowingStateLoss()
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            val playFragment =
                supportFragmentManager.findFragmentByTag(PlayFragment::class.java.name) as? PlayFragment
            playFragment?.onVolumeChange(true)
            return true
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            val playFragment =
                supportFragmentManager.findFragmentByTag(PlayFragment::class.java.name) as? PlayFragment
            playFragment?.onVolumeChange(false)
            return true
        }
        return super.onKeyUp(keyCode, event)
    }

//    override fun onBackPressed() {
//        val intent = Intent(Intent.ACTION_MAIN);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.addCategory(Intent.CATEGORY_HOME);
//        startActivity(intent);
//    }
}

